import URLPattern from "url-pattern"
import {decodeAccessToken} from "~/server/utils/jwt.js";
import {getUserById} from "~/server/db/users.js";

export  default defineEventHandler(async (event)=>{
    const endpoints = [  '/api/auth/user',
        '/api/user/tweets',
        '/api/tweets',
        '/api/tweets/:id']
    const isHandledByThisMiddleware = endpoints.some(endpoints=>{
        const pattern = new URLPattern(endpoints)
        return pattern.match(event.node.req.url)
    })
    if (!isHandledByThisMiddleware) return;
    // 从请求中拿到token 通过token解码userid
    const token = event.node.req.headers['authorization']?.split(' ')[1]
    const decoded = decodeAccessToken(token)
    if (!decoded) {
        return sendError(event, createError({
            statusCode: 401,
            statusMessage: 'Unauthorized'
        }))
    }
    try {
        const userId = decoded.userId

        const user = await getUserById(userId)
        // 绑定到  event上下文中  后续在endpoints请求中可以拿到用户信息
        event.context.auth = { user }
    } catch (error) {
        return
    }

})